import tensorflow as tf
from tensorflow.keras import layers, models

BATCH_SIZE = 100


def load_image(img_path,size = (32,32)):
    label = tf.constant(1,tf.int8) if tf.strings.regex_full_match(img_path,".*automobile.*") \
            else tf.constant(0,tf.int8)
    img = tf.io.read_file(img_path) # input output 一列数
    img = tf.image.decode_jpeg(img) #注意此处为jpeg格式 # 计算个数
    img = tf.image.resize(img,size)/255.0
    return(img,label)

# 从文件数据创建路径管道
#使用并行化预处理num_parallel_calls 和预存数据prefetch来提升性能
#shuffle:数据顺序洗牌。
# 使用 map 时设置num_parallel_calls 让数据转换过程多进程执行。
# 使用 map转换时，先batch, 然后采用向量化的转换方法对每个batch进行转换。
# 使用 prefetch 方法让数据准备和参数迭代两个过程相互并行。
ds_train = tf.data.Dataset.list_files("../data/cifar2/train/*/*.jpg") \
           .map(load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE) \
           .shuffle(buffer_size = 1000).batch(BATCH_SIZE) \
           .prefetch(tf.data.experimental.AUTOTUNE)

ds_test = tf.data.Dataset.list_files("../data/cifar2/test/*/*.jpg") \
           .map(load_image, num_parallel_calls=tf.data.experimental.AUTOTUNE) \
           .batch(BATCH_SIZE) \
            .prefetch(tf.data.experimental.AUTOTUNE)

#查看部分样本
from matplotlib import pyplot as plt

plt.figure(figsize=(8,8))
for i,(img,label) in enumerate(ds_train.unbatch().take(7)):
    ax=plt.subplot(3,3,i+1)
    ax.imshow(img.numpy()) # 显示图片
    ax.set_title("label = %d"%label)
    ax.set_xticks([])
    ax.set_yticks([])
plt.show()

for x,y in ds_train.take(1):
    print(x.shape,y.shape)

# 定义模型
tf.keras.backend.clear_session() #清空会话

inputs = layers.Input(shape=(32,32,3))
x = layers.Conv2D(32,kernel_size=(3,3))(inputs)
x = layers.MaxPool2D()(x)
x = layers.Conv2D(64,kernel_size=(5,5))(x)
x = layers.MaxPool2D()(x)
x = layers.Dropout(rate=0.1)(x)
x = layers.Flatten()(x)
x = layers.Dense(32,activation='relu')(x)
outputs = layers.Dense(1,activation = 'sigmoid')(x)

model = models.Model(inputs = inputs,outputs = outputs)
model.summary()

# 训练模型
import datetime
import os

stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
logdir = os.path.join('data', 'autograph', stamp)

## 在 Python3 下建议使用 pathlib 修正各操作系统的路径
# from pathlib import Path
# stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
# logdir = str(Path('./data/autograph/' + stamp))

tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)

model.compile(
        optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
        loss=tf.keras.losses.binary_crossentropy,
        metrics=["accuracy"]
    )

history = model.fit(ds_train,epochs= 2,validation_data=ds_test,
                    callbacks = [tensorboard_callback],workers = 4)

# 评估模型
from tensorboard import notebook
notebook.list()

notebook.start("--logdir \"" + logdir + "\" --port 6005")

import pandas as pd
dfhistory = pd.DataFrame(history.history)
dfhistory.index = range(1,len(dfhistory) + 1)
dfhistory.index.name = 'epoch'

import matplotlib.pyplot as plt

def plot_metric(history, metric):
    global i
    i += 1
    plt.subplot(3, 3, i + 1)
    train_metrics = history.history[metric]
    val_metrics = history.history['val_'+metric]
    epochs = range(1, len(train_metrics) + 1)
    plt.plot(epochs, train_metrics, 'bo--')
    plt.plot(epochs, val_metrics, 'ro-')
    plt.title('Training and validation '+ metric)
    plt.xlabel("Epochs")
    plt.ylabel(metric)
    plt.legend(["train_"+metric, 'val_' + metric])
    plt.show()

plot_metric(history,"loss")

plot_metric(history,"accuracy")

val_loss,val_accuracy = model.evaluate(ds_test,workers=4)
print(val_loss,val_accuracy)

# 可以使用model.predict(ds_test)进行预测。
#
# 也可以使用model.predict_on_batch(x_test)对一个批量进行预测。

model.predict(ds_test)

for x,y in ds_test.take(1):
    print(model.predict_on_batch( x[0:20]))


# 保存模型
model.save('./data/tf_model_savedmodel', save_format="tf")
print('export saved model.')
# 加载模型
model_loaded = tf.keras.models.load_model('./data/tf_model_savedmodel')
print(model_loaded.evaluate(ds_test))

# tensorboard --logdir=E:\py-code\DL2\day05CNN+VGG\data\autograph\20210324-231428\train --host=127.0.0.1







